package org.power.core.util;

import cn.hutool.core.text.csv.*;
import cn.hutool.core.util.CharsetUtil;
import org.power.core.config.PowerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Paths;
import java.util.List;

@Component
public class CsvUtils {
    /**
     * 导出csv格式工具类
     *
     * @param result   导出数据
     * @param fileName 文件名
     */
    public static boolean createCsvFile(List<String[]> result, String path, String fileName) {
        try {

            System.out.println(Paths.get(path, "temp_" + fileName).toString());
            File csvFile = new File(Paths.get(path, "temp_" + fileName).toString());  //构造文件
            //导入HuTool中CSV工具包的CsvWriter类
            //设置导出字符类型, CHARSET_UTF_8
            CsvWriter writer = CsvUtil.getWriter(csvFile, CharsetUtil.CHARSET_UTF_8);

            writer.write(result);  //通过CsvWriter中的write方法写入数据
            writer.close();   //关闭CsvWriter
            //保存文件
            FileInputStream fileInputStream = new FileInputStream(csvFile);
            saveFile(fileInputStream, path, fileName);
            return true;
        } catch (Exception e) {
            System.out.println(e);
        }
        return false;
    }

    /**
     * 文件保存
     *
     * @param inputStream
     * @param fileName
     */
    private static void saveFile(InputStream inputStream, String path, String fileName) {
        OutputStream os = null;
        try {
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                boolean rst = tempFile.mkdirs();
            }
            // 创建最终生成的文件
            String fullFilePath = tempFile.getPath() + File.separator + fileName;

            System.out.println("*******************************************");
            System.out.println(fullFilePath);
            System.out.println("*******************************************");

            FileUtil.createFile(fullFilePath);

            os = new FileOutputStream(fullFilePath);

            // resolved File garbled problem
            // 参考：https://blog.csdn.net/qq_42761569/article/details/118894380
            // 先写入 UTF-8-BOM 编码头内容
            byte[] uft8bom = {(byte) 0xef, (byte) 0xbb, (byte) 0xbf};
            os.write(uft8bom);

            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static List<CsvRow> read(String csvFile) {
        CsvReader reader = CsvUtil.getReader();
        CsvData data = reader.read(new File(csvFile), CharsetUtil.CHARSET_UTF_8);
        List<CsvRow> rows = data.getRows();
        return rows;
    }
}
